package com.example.demo.core.listener;

import com.example.demo.core.event.EmailEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class EmailListener {

  protected final Log logger = LogFactory.getLog(getClass());
  /**
   * @param event
   */
  @EventListener
  public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof EmailEvent) {
      EmailEvent emailEvent = (EmailEvent) event;
      emailEvent.print();
      if (logger.isDebugEnabled()) {
        logger.error("debug log can show when log level is debug");
      }
      System.out.println("the source is:" + emailEvent.getSource());
      System.out.println("the address is:" + emailEvent.getAddress());
      System.out.println("the email's context is:" + emailEvent.getText());
    }
  }


  /**
   * 这个处理过程不应该在主业务流程中,直接异步去处理。加注解
   * @param emailEvent
   */
  //@EventListener
  //@Async
  public void listener(EmailEvent emailEvent) {
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("异步处理:");
    emailEvent.print();
    System.out.println("the source is:" + emailEvent.getSource());
    System.out.println("the address is:" + emailEvent.getAddress());
    System.out.println("the email's context is:" + emailEvent.getText());
  }
}